package cn.hd01.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.hd01.repository.CustomerRepository;
import cn.hd01.repository.entity.Customer;
import cn.hd01.service.CustomerService;
import cn.hd01.web.entity.CustomerQuery;

@Service
public class CustomerServiceImpl extends BaseServiceImpl<Customer, Integer> implements CustomerService {

	private CustomerRepository repository;

	@Autowired
	public CustomerServiceImpl(CustomerRepository repository) {
		super(repository);
		this.repository = repository;
	}

	@Override
	public Page<Customer> find(final CustomerQuery query, Pageable pageable) {
		if (query == null) {
			return repository.findAll(pageable);
		}

		return repository.findAll(Specifications.where(new Specification<Customer>() {
			@Override
			public Predicate toPredicate(Root<Customer> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<Predicate>();

				if (StringUtils.hasText(query.getName())) {
					predicates.add(cb.like(r.get("name").as(String.class), "%" + query.getName() + "%"));
				}

				if (StringUtils.hasText(query.getWeixin())) {
					predicates.add(cb.like(r.get("weixin").as(String.class), "%" + query.getWeixin() + "%"));
				}

				if (StringUtils.hasText(query.getPhone())) {
					predicates.add(cb.like(r.get("phone").as(String.class), "%" + query.getPhone() + "%"));
				}

				if (StringUtils.hasText(query.getHospital())) {
					predicates.add(cb.like(r.get("hospital").as(String.class), "%" + query.getHospital() + "%"));
				}

				if (StringUtils.hasText(query.getStore())) {
					predicates.add(cb.equal(r.get("store").as(String.class), query.getStore()));
				}

				if (StringUtils.hasText(query.getSex())) {
					predicates.add(cb.equal(r.get("sex").as(String.class), query.getSex()));
				}

				if (query.getBeginCreateTime() != null && query.getEndCreateTime() != null) {
					predicates.add(cb.between(r.get("creatTime").as(Date.class), query.getBeginCreateTime(),
							query.getEndCreateTime()));
				}

				return cb.and(predicates.toArray(new Predicate[] {}));
			}
		}), pageable);
	}
}
